import React, {useRef, useState, useEffect} from 'react';
import type {TooltipProps} from 'antd/lib/tooltip';
import {Tooltip} from 'antd';

/**
 * 超出宽度鼠标悬浮显示tooltip
 * @returns
 */
const HoverTooltip = (props: TooltipProps) => {
    const {title, children, ...rest} = props;
    const ref = useRef<HTMLDivElement>(null);
    // 是否显示tooltip
    const [show, setShow] = useState(false);
    // 显示省略号的样式
    const ellipsisStyle: React.CSSProperties = {
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        whiteSpace: 'nowrap',
        verticalAlign: 'middle',
        maxWidth: '100%',
        textAlign: 'center',
    };

    // 判断是否需要显示省略号
    const isEllipsis = () => {
        const parentDom = ref.current;
        if (!parentDom) return false;
        const {offsetWidth, scrollWidth} = parentDom;
        return offsetWidth < scrollWidth;
    };

    useEffect(() => {
        // 设置父元素为hidden
        ref.current?.parentElement?.setAttribute('style', 'overflow: hidden;');
    }, [children]);

    useEffect(() => {
        setShow(isEllipsis());
    });

    return (
        <Tooltip title={show ? title || children : null} {...rest}>
            <div ref={ref} style={ellipsisStyle}>
                {children}
            </div>
        </Tooltip>
    );
};

export default HoverTooltip;
